package com.example.bai15;

import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import org.w3c.dom.*;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }
        Button btndom,btnsax;
        Spinner spinner;
        ListView list;
        ArrayAdapter<String> adapter,sadapter;
        ArrayList<String> arr,sarr;
        String fname;
        /*   false-dom
             true-sax */
        Boolean flag;
        static Boolean DOM=false;
        static Boolean SAX=true;
        static String ALL="%";
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
		@Override
		public void onStart() {
			// TODO Auto-generated method stub
			super.onStart();
			btndom = (Button) getActivity().findViewById(R.id.btndom);
			btnsax = (Button) getActivity().findViewById(R.id.btnsax);
			
			list=(ListView) getActivity().findViewById(R.id.listView1);
			arr= new ArrayList<String>();
			adapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,arr);
			list.setAdapter(adapter);
			
			spinner= (Spinner) getActivity().findViewById(R.id.spinner);
			sarr= new ArrayList<String>();
			sadapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,sarr);
			spinner.setAdapter(sadapter);
			
			//String sdcard= Environment.getExternalStorageDirectory().getAbsolutePath();
			 
		
			URL tmp=MainActivity.class.getResource("data.xml");
			fname=tmp.getFile();
			//fname="src/com/example/bai15/data.xml";
			
			addEvents();
		}
		private void clearList()
		{
			arr.clear();
			adapter.notifyDataSetChanged();
		}
		private void proccessButtonOnClick(Boolean _flag)
		{
			sarr.clear();
			sadapter.notifyDataSetChanged();
			if(_flag==DOM)
			getListByDom(ALL);
			else
				getListBySax(ALL);
			flag=_flag;
			sadapter.notifyDataSetChanged();
		}
		private void addEvents()
		{
			btndom.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					proccessButtonOnClick(DOM);
				}
			});
			
			btnsax.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					proccessButtonOnClick(SAX);
				}
			});
			
			spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					clearList();
					if(flag.equals(DOM))
					{
						getListBySax(sarr.get(position));
					}
					else
					{
						getListByDom(sarr.get(position));
					}
					adapter.notifyDataSetChanged();
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
					// TODO Auto-generated method stub
					clearList();
				}
			});
			
			
		}
		private void getListByDom(String para)
		{
			try {
				DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
				DocumentBuilder builder= factory.newDocumentBuilder();
				Document doc=builder.parse(fname);
				Element eroot= doc.getDocumentElement();
				NodeList nlist=eroot.getChildNodes();
				for(int i=0;i<nlist.getLength();i++)
				{
					Node node=nlist.item(i);
					if(node instanceof Element)
					{
						Element e= (Element) node;
						String title=e.getAttribute("title");
						if(para.equalsIgnoreCase(ALL))
						{
							if(!sarr.contains(title))
							{
								sarr.add(title);
							}
						}
						else
						{
							if(title.equalsIgnoreCase(para))
							{
								String id=e.getAttribute("id");
								NodeList clist=e.getElementsByTagName("name");
								String name=clist.item(0).getTextContent();
								 clist=e.getElementsByTagName("phone");
								String phone=clist.item(0).getTextContent();
								String restext=id+" - "+name+" - "+phone;
								arr.add(restext);
							}
						}
					}
				}
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
			Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
		private void getListBySax(String para)
		{
			try {
				XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
				XmlPullParser parser=factory.newPullParser();
				FileInputStream fin= new FileInputStream(fname);
				parser.setInput(fin, "UTF-8");
				int eventType=-1;
				Boolean e=false;
				String data="";
				while(eventType!=XmlPullParser.END_DOCUMENT)
				{
					eventType=parser.next();
					switch(eventType)
					{
						case XmlPullParser.END_DOCUMENT:
							break;
						case XmlPullParser.START_TAG:
						{	
							
							String nname=parser.getName();
							if(nname.equalsIgnoreCase("employee"))
							{
								String title=parser.getAttributeValue(1);
								if(para.equalsIgnoreCase(ALL))
								{
									
									if(!sarr.contains(title))
									{
										sarr.add(title);
									}
								}
								else
								{
									if(title.equalsIgnoreCase(para))
									{
										e=true;
										data+=parser.getAttributeValue(0)+" - ";
									}
								}
							}
								if(e)
								{
									if(nname.equalsIgnoreCase("name"))
									{
										data+=parser.getText()+" - ";
									}
									if(nname.equalsIgnoreCase("phone"))
									{
										data+=parser.getText()+" - ";
									}
								}
						}
						case XmlPullParser.END_TAG:
							String nname=parser.getName();
							if(nname.equalsIgnoreCase("employee"))
							{
								e=false;
								arr.add(data);
							}
					}
					
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();			}
			
		}
    }

}
